package com.sk.weichat.ui.me.redpacket;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import com.facebook.drawee.view.SimpleDraweeView;
import com.githang.statusbar.StatusBarCompat;
import com.sk.weichat.R;
import com.sk.weichat.bean.redpacket.EventRedReceivedStatus;
import com.sk.weichat.bean.redpacket.RedpacketDetailBean;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.ui.me.PersonalCenterActivity;
import com.sk.weichat.ui.tool.WebViewActivity;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.util.ScreenUtil;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import org.minidns.record.A;

import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;
import okhttp3.Call;

/**
 * modify by lzs 群聊
 */
public class MucRedPacketDetailsActivity extends BaseActivity {

    static Map<Integer, String> statusMap = new HashMap<>();

    static {
        statusMap.put(RedpacketDetailBean.Status_unopen, "");
        statusMap.put(RedpacketDetailBean.Status_empty, "已抢光");
        statusMap.put(RedpacketDetailBean.Status_refunded, "已过期");
        statusMap.put(RedpacketDetailBean.Status_opened, "");
        statusMap.put(RedpacketDetailBean.Status_expire, "");
    }


    public static final void startRedPacketDetailsActivity(Context context, RedpacketDetailBean redpacketDetailBean) {
        Intent intent = new Intent(context, MucRedPacketDetailsActivity.class);
        intent.putExtra(RedpacketDetailBean.RedpacketDetailBean_Key, redpacketDetailBean);
        context.startActivity(intent);
    }

//    public static final void startRedPacketDetailsActivityOptions(Context context, RedpacketDetailBean redpacketDetailBean, Bundle options) {
//        Intent intent = new Intent(context, MucRedPacketDetailsActivity.class);
//        intent.putExtra(RedpacketDetailBean.RedpacketDetailBean_Key, redpacketDetailBean);
//        context.startActivity(intent, options);
//    }

    RedpacketDetailBean redpacketDetailBean;
    //红包金额
    TextView tvMoney;
    //人民币符号
    TextView tvYuan;

    boolean isOwner;
    boolean isGroup;
    //是否领取过
    boolean isOpened;
    boolean isRandom;
    //红包状态
    int status = -1;
    List<RedpacketDetailBean.ReceiveListBean> receiveListBeans = new ArrayList<>();
    BaseQuickAdapter<RedpacketDetailBean.ReceiveListBean, BaseViewHolder> adapter;
    NumberFormat numberFormat = new DecimalFormat("0.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_redpacket_details);
        //浅色状态栏字体图标
        StatusBarCompat.setLightStatusBar(getWindow(), false);
        ImageView ivBack = findViewById(R.id.iv_back);
        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) ivBack.getLayoutParams();
        lp.topMargin += ScreenUtil.getStatusHeight(mContext);
        ivBack.setLayoutParams(lp);
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.tv_record).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转交易记录
                String url = coreManager.getConfig().TRADE_RECORDE + "?access_token=" + coreManager.getSelfStatus().accessToken + "&time=" + System.currentTimeMillis() / 1000;
                WebViewActivity.start(mContext, url, false);
            }
        });
        redpacketDetailBean = getIntent() != null ? getIntent().getParcelableExtra(RedpacketDetailBean.RedpacketDetailBean_Key) : null;
        if (null != redpacketDetailBean) {
            status = redpacketDetailBean.getStatus();
            //发红包者id
            String fromId = String.valueOf(redpacketDetailBean.getUserId());
            //当前用户是否是发送者
            isOwner = fromId.equals(coreManager.getSelf().getUserId());
            //是否群聊
            isGroup = !TextUtils.isEmpty(redpacketDetailBean.getRoomId());
            //是否领取过
            isOpened = status == RedpacketDetailBean.Status_opened;
            // 是否拼手气红包
            isRandom = redpacketDetailBean.getType() == RedpacketDetailBean.type_random;

            RecyclerView recyclerView = findViewById(R.id.recyclerview);
            recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
            adapter = new BaseQuickAdapter<RedpacketDetailBean.ReceiveListBean, BaseViewHolder>(R.layout.item_red_packet_details_reciever, receiveListBeans) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                @Override
                protected void convert(BaseViewHolder holder, RedpacketDetailBean.ReceiveListBean item) {
                    holder.addOnClickListener(R.id.iv_avatar);
                    //头像
                    FrescoUtils.loadImage((SimpleDraweeView) holder.getView(R.id.iv_avatar), AvatarHelper.getAvatarUrl(item.getUserId() + "", true));
                    holder.setText(R.id.tv_name, item.getNickname());
                    //时间
                    holder.setText(R.id.tv_time, sdf.format(new Date(item.getReceiveTime() * 1000)));
                    //
                    holder.setText(R.id.tv_money, numberFormat.format(item.getReceiveMoney()) + " 元");
                    //判断是否是最佳
                    if (item.getIsMost() == 0) {
                        holder.setTextColor(R.id.tv_money, getResources().getColor(R.color.text_color_main));
                        holder.getView(R.id.tv_best).setVisibility(View.INVISIBLE);
                    } else {
                        holder.getView(R.id.tv_best).setVisibility(View.VISIBLE);
                        holder.setTextColor(R.id.tv_money, getResources().getColor(R.color.color_ff2626));
                    }
                }
            };
            adapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
                @Override
                public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if (view.getId() == R.id.iv_avatar) {
                        PersonalCenterActivity.start(mContext, receiveListBeans.get(position).getUserId() + "");
                    }
                }
            });

            View headerView = LayoutInflater.from(mContext).inflate(R.layout.layout_header_redpacket, null);
            //头像
            SimpleDraweeView ivAvatar = headerView.findViewById(R.id.iv_avatar);
            FrescoUtils.loadImage(ivAvatar, AvatarHelper.getAvatarUrl(redpacketDetailBean.getUserId() + "", true));
            ivAvatar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    PersonalCenterActivity.start(mContext, redpacketDetailBean.getUserId() + "");
                }
            });
            //昵称
            TextView tvName = headerView.findViewById(R.id.tv_name);
            tvName.setText(redpacketDetailBean.getNickname() + " 的红包");

            if (isRandom) {
                //拼手气红包，显示拼手气
                Drawable drawable = getResources().getDrawable(R.mipmap.icon_pin);
                drawable.setBounds(new Rect(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()));
                tvName.setCompoundDrawables(null, null, drawable, null);
            } else {
                ConstraintLayout.LayoutParams lp2 = (ConstraintLayout.LayoutParams) tvName.getLayoutParams();
                lp2.leftMargin = 0;
                tvName.setLayoutParams(lp2);
            }
            //红包内容
            TextView tvContent = headerView.findViewById(R.id.tv_content);
            tvContent.setText(redpacketDetailBean.getGreetings());
            tvMoney = headerView.findViewById(R.id.tv_money);
            tvYuan = headerView.findViewById(R.id.tv_yuan);
            //设置金额
            setMoney();
            //红包状态
            TextView tvStatus = headerView.findViewById(R.id.tv_status);
            tvStatus.setText(statusMap.get(redpacketDetailBean.getStatus()));
            //已领取个数
            TextView tvDesc = headerView.findViewById(R.id.tv_desc);
            if (redpacketDetailBean.getCount() == redpacketDetailBean.getReceiveCount()) {
                //已抢光
                tvDesc.setText("已领取" + redpacketDetailBean.getReceiveCount() + "个，" + caculateTime(redpacketDetailBean.getSendTime(), redpacketDetailBean.getEndTime()) + "被抢光");
            } else {
                //未抢光
                tvDesc.setText("已领取" + redpacketDetailBean.getReceiveCount() + "个");
            }
            TextView tvTotal = headerView.findViewById(R.id.tv_total);
            if (coreManager.getSelf().getUserId().equals(String.valueOf(redpacketDetailBean.getUserId()))) {
                //发红包者自己，可以看到总金额
                tvTotal.setText("共" + redpacketDetailBean.getCount() + "个，总金额" + numberFormat.format(redpacketDetailBean.getMoney()) + "元");
            } else {
                //其他用户
                tvTotal.setText("共" + redpacketDetailBean.getCount() + "个");
            }
            adapter.addHeaderView(headerView);
            recyclerView.setAdapter(adapter);
            //获取红包详情
            getDetails(redpacketDetailBean.getId());
        }

    }

    private void setMoney() {
        if (isRandom && isGroup && isOwner && status == RedpacketDetailBean.Status_opened || isRandom && !isOwner && status == RedpacketDetailBean.Status_opened) {
            tvMoney.setVisibility(View.VISIBLE);
            tvYuan.setVisibility(View.VISIBLE);
            //显示领取金额
            tvMoney.setText(numberFormat.format(redpacketDetailBean.getReceiveMoney()) + "");
        } else if (!isRandom && isGroup && isOwner && status == RedpacketDetailBean.Status_opened || !isRandom && isGroup && isOwner && status == RedpacketDetailBean.Status_unopen || isRandom && isOwner && status == RedpacketDetailBean.Status_unopen) {
            tvYuan.setVisibility(View.GONE);
            tvMoney.setVisibility(View.GONE);

        } else if (isRandom && isOwner && status != RedpacketDetailBean.Status_empty && status != RedpacketDetailBean.Status_refunded) {
            tvMoney.setVisibility(View.VISIBLE);
            tvYuan.setVisibility(View.VISIBLE);
            //tvMoney.setText(redpacketDetailBean.getReceiveMoney() + "");
        } else {
            tvYuan.setVisibility(View.INVISIBLE);
            tvMoney.setVisibility(View.INVISIBLE);
        }
    }

    private String caculateTime(long sendTime, long endTime) {
        long time = endTime - sendTime;
        if (time / 60 == 0) {
            return time + "秒";
        } else if (time / 60 / 60 == 0) {
            return time / 60 + "分钟";
        } else {
            return time / 60 / 60 + "小时";
        }
    }


    // 点击红包 查询红包状态
    public void getDetails(String id) {
        final String token = CoreManager.requireSelfStatus(mContext).accessToken;
        HashMap<String, String> params = new HashMap<>();
        params.put("access_token", token);
        params.put("id", id);
        HttpUtils.post().url(CoreManager.requireConfig(mContext).RENDPACKET_GET)
                .params(params)
                .build()
                .execute(new BaseCallback<RedpacketDetailBean>(RedpacketDetailBean.class) {

                    @Override
                    public void onResponse(ObjectResult<RedpacketDetailBean> result) {
                        if (result.getResultCode() == 1 && result.getData() != null) {
                            receiveListBeans.clear();
                            receiveListBeans.addAll(result.getData().getReceiveList());
                            adapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                    }
                });
    }

}
